package com.crl.utils
{
	import com.crl.utils.describe.DescribeTypeCache;
	import com.crl.utils.describe.VariablesInfo;
	
	import flash.net.registerClassAlias;
	import flash.utils.ByteArray;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	
	/**
	 * 
	 * @author crl
	 * 
	 */	
	public class ObjectUtil
	{
		public function ObjectUtil()
		{
		}
		
		
		public static function getString(value:Object,defaultValue:String=""):String{
			if(value==null){
				return defaultValue;
			}
			
			//因为数字的0也等于空字符串;
			if(value is String && value==""){
				return defaultValue;
			}
			
			return value.toString();
		}
		
		public static function getBoolean(value:Object):Boolean{
			return Boolean(value);
		}
		
		
		public static function getInt(value:Object,defaultValue:int=-1):int{
			if(value==null){
				return defaultValue;
			}
			return int(value);
		}
		
		public static function getNumber(value:Object ,defaultValue:Number=-1):Number{
			if(value==null){
				return defaultValue;
			}
			
			return Number(value);
		}
		
		
		/**
		 * 由一个对像生成一个类对像,因为o有可能也为一个类对像,所以直接用了 DescribeTypeCache来取得类属性列表;
		 * @param o key value 对应对像;
		 * @param c 返回的类型;
		 * @return  返回类;
		 * 
		 */		
		public static function getClassInstancebyObject(o:Object,c:Class):*{
			var cls :* = new c();
			
			if(o==null){
				return cls;
			}
			
			var defineFullClsName:String=getQualifiedClassName(o);
			if(defineFullClsName=="Object"){
				var variablesInfo :VariablesInfo = DescribeTypeCache.describeType(cls).variablesInfo;
				var propertys : Array = variablesInfo.getPropertys();
			}
			for each(var propName:String  in propertys)
			{
				if(o.hasOwnProperty(propName)){
					cls[propName] = o[propName];
				}
			}
			return cls;
		}
		
		/**
		 * 是否为简单类型.
		 * @param value
		 * @return 
		 * 
		 */		
		public static function isSimple(value:Object):Boolean
		{
			var type:String = typeof(value);
			switch (type)
			{
				case "number":
				case "string":
				case "boolean":
				{
					return true;
				}
					
				case "object":
				{
					return (value is Date) || (value is Array);
				}
			}
			
			return false;
		}
		
		
		/**
		 * 深度复制; 
		 * @param obj
		 * @return 
		 * 
		 */		
		public static function deepClone(value:Object):Object{
			var fullName:String = getQualifiedClassName(value);
			var className:String = fullName.search("::") > -1 ? fullName.split("::")[1] : fullName;
			var definition:Class = getDefinitionByName(fullName) as Class;
			registerClassAlias(className, definition);
			var buffer:ByteArray = new ByteArray();
			buffer.writeObject(value);
			buffer.position = 0;
			var result:Object = buffer.readObject();
			return result;
		}
	}
}